import * as React from 'react'
import {Modal, notification} from 'antd'
import {ExclamationCircleOutlined} from '@ant-design/icons'
import {ArgsProps} from "antd/lib/notification"
import {ModalFuncProps} from "antd/es/modal/Modal"
import {message as AntdMessage} from 'antd'
import {MessageType} from "antd/es/message"
import _ from 'lodash'
import {isPromise, isReact} from "..";
import {ReactElement, ReactNode} from "react";

let GLOBAL_HIDE: undefined | MessageType = undefined
export declare type ModalFuncPlus = (props: ModalFuncProps | string | ReactElement) => {
    destroy: () => void;
    update: (newConfig: ModalFuncProps) => void;
};

export function loading(msg?: string) {
    clearLoading();
    GLOBAL_HIDE = AntdMessage.loading({
        content: msg || '加载中...',
        duration: 0,
        style: {
            marginTop: '20vh',
        },
    })
}

export function clearLoading() {
    if (GLOBAL_HIDE) {
        GLOBAL_HIDE()
    }
}

/**
 * 弹出确认框
 * @param content 需要确认的文字内容
 */
export function confirm<T>(content: string | ReactElement, onOk?: () => Promise<T>, onCancel?: () => any): Promise<void> {
    if (typeof onOk === 'function') {
        Modal.confirm({
            title: "请确认",
            icon: <ExclamationCircleOutlined/>,
            content: content,
            okText: '确认',
            cancelText: '取消',
            onOk,
            onCancel
        })
        return new Promise<void>((resolve, reject) => {
        })

    } else {
        // 传统方式
        return new Promise<void>((resolve, reject) => {
            Modal.confirm({
                title: "请确认",
                icon: <ExclamationCircleOutlined/>,
                content: content,
                okText: '确认',
                cancelText: '取消',
                onOk: () => {
                    resolve()
                },
                onCancel: () => {
                    reject()
                }
            });
        })
    }
}

/**
 * 显示一个模态对话框，用于强提醒
 */
export const showSuccessDialog: ModalFuncPlus = (prop) => {
    if (typeof prop === 'string' || isReact(prop)) {
        return Modal.success({title: '成功', content: prop})
    }
    return Modal.success(prop)
}

/**
 * 显示一个模态对话框，用于强提醒
 */
export const showWarningDialog: ModalFuncPlus = (prop) => {
    if (typeof prop === 'string' || isReact(prop)) {
        return Modal.warning({title: '警告', content: prop})
    }
    return Modal.warning(prop)
}

/**
 * 显示一个模态对话框，用于强提醒
 */
export const showInfoDialog: ModalFuncPlus = (prop) => {
    if (typeof prop === 'string' || isReact(prop)) {
        return Modal.info({title: '提示', content: prop})
    }
    return Modal.info(prop)
}

/**
 * 显示一个模态对话框，用于强提醒
 */
export const showErrorDialog: ModalFuncPlus = (prop) => {
    if (typeof prop === 'string' || isReact(prop)) {
        return Modal.error({title: '错误', content: prop})
    }
    return Modal.error(prop)
}

/**
 * 显示一个能自动关闭的浮动层
 */
export function showSuccess(msg: string | ReactElement) {
    return AntdMessage.success(msg)
}

/**
 * 显示一个能自动关闭的浮动层
 */
export function showWarning(msg: string | ReactElement) {
    return AntdMessage.warning(msg)
}

/**
 * 显示一个能自动关闭的浮动层
 */
export function showInfo(msg: string | ReactElement) {
    return AntdMessage.info(msg)
}

/**
 * 显示一个能自动关闭的浮动层
 */
export function showError(msg: string | ReactElement) {
    return AntdMessage.error(msg)
}

/**
 * 在角落显示一条消息提醒
 */
export function notifySuccess(args: ArgsProps | string | ReactElement) {
    if (typeof args === 'string' || isReact(args)) {
        return notification.success({message: args, description: '成功', placement: 'topRight'})
    }
    return notification.success(args)
}

/**
 * 在角落显示一条消息提醒
 */
export function notifyWarning(args: ArgsProps | string | ReactElement) {
    if (typeof args === 'string' || isReact(args)) {
        return notification.warning({message: args, description: '警告', placement: 'topRight'})
    }
    return notification.warning(args)
}

/**
 * 在角落显示一条消息提醒
 */
export function notifyInfo(args: ArgsProps | string | ReactElement) {
    if (typeof args === 'string' || isReact(args)) {
        return notification.info({message: args, description: '提示', placement: 'topRight'})
    }
    return notification.info(args)
}

/**
 * 在角落显示一条消息提醒
 */
export function notifyError(args: ArgsProps | string | ReactElement) {
    if (typeof args === 'string' || isReact(args)) {
        return notification.error({message: args, placement: 'topRight'})
    }
    return notification.error(args)
}

function getValidateMsgList(e: any) {
    const {errorFields} = e
    const msgList: string[] = []
    for (let i = 0; i < errorFields.length; i++) {
        const {errors} = errorFields[i]
        msgList.splice(msgList.length, 0, ...errors)
    }
    return msgList
}

/**
 * 以通知的方式告知用户，校验异常
 */
export function showValidateErrorDialog(sender: any, e: any) {
    console.log(sender)
    // const msgList = getValidateMsgList(e)
    notifyError({
        key: 'validate-notify',
        message: '校验没有通过',
        className: 'notify-error',
        description: (<ul className="notify-error-list-wrap">
            {
                ..._.map(e.errorFields, (errorDetail) =>

                    <li key={_.uniqueId('_')} onClick={ssclick(e.errorFields, errorDetail)}>{errorDetail.errors}</li>
                )
            }
        </ul>),
        duration: 0
    })

    function ssclick(errorFields: any[], errorDetail: any): any {
        console.log(errorDetail);
        return () => {

            let repeatIndex = -1;
            for (let i = 0; i < errorFields.length; i++) {
                const el = errorFields[i];
                if (errorDetail.name[0] === el.name[0]) {
                    repeatIndex++;
                }
                if (el === errorDetail) {
                    break
                }
            }
            const tagArr = document.querySelectorAll("[id='" + errorDetail.name[0] + "']");
            $(tagArr[repeatIndex]).focus();
            // console.log(tagArr[repeatIndex])
            //sender.scrollToField()
        }
    }

    // showErrorDialog({
    //     title: '校验没有通过',
    //     content: (<ul>
    //         {
    //             ..._.map(msgList, msg =>
    //                 <li key={_.uniqueId('_')} onClick={()=>{
    //                     //debugger
    //                 }}>{msg}</li>
    //             )
    //         }
    //     </ul>)
    // })
}

/**
 * 以通知的方式告知用户，校验异常
 */
export function notifyValidateError(e: any) {
    const msgList = getValidateMsgList(e)

    notifyError({
        message: '校验没有通过',
        key: 'ValidateError',
        description: (<ul>
            {
                ..._.map(msgList, msg =>
                    <li key={_.uniqueId('_')}>{msg}</li>
                )
            }
        </ul>),
        duration: 0
    })
}

/**
 * 动态设置form组件label的颜色
 */
export function changeLabel(ctl: any, style: any) {
    $('div[view_id=' + ctl.key + ']').find('label').css(style)
}

export function changeTabKey(ctl: any,key: any) {
    $('div[view_id='+ctl.key+']').find('.ant-tabs-tab').eq(key).trigger('click');
}

/**
 * 动态隐藏/显示组件
 */
 export function displayComponent(ctl: any, type: any) {
     if(type=='hide'){
        $('div[view_id=' + ctl.key + ']').parent().hide();
     }else if(type=='show'){
        $('div[view_id=' + ctl.key + ']').parent().show();
     }
    
}